package com.huashi.dealer.modular.controller.api.order;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.Order;
import com.huashi.dealer.commonEntity.OrderExpress;
import com.huashi.dealer.core.page.PageFactory;
import com.huashi.dealer.core.pojo.CommonResult;
import com.huashi.dealer.modular.business.order.param.*;
import com.huashi.dealer.modular.business.order.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.huashi.dealer.modular.business.order.bo.OrderAuditBo;

/**
 * API订单控制器
 *
 * @author 谭陈强
 * @since 2025-07-30
 */
@Tag(name = "API订单控制器")
@RestController("apiOrderController")
@RequestMapping("/api/order")
@Validated
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
	 * 立即购买（POST）
	 */
	@PostMapping("/buyNow")
	@Operation(summary = "立即购买")
	public CommonResult<OrderResponseParam> buyNow(@RequestBody OrderRequestParam requestParam) {
		try {
			OrderResponseParam responseParam = orderService.buyNow(requestParam);
			return CommonResult.data(responseParam);
		} catch (Exception e) {
			return CommonResult.error("立即购买失败：" + e.getMessage());
		}
	}

	/**
	 * 立即购买（GET，与历史PHP接口兼容）
	 */
	@GetMapping("/buyNow")
	@Operation(summary = "立即购买（GET）")
	public CommonResult<OrderResponseParam> buyNowGet(@RequestParam String goodsIds,
														 @RequestParam(required = false) Integer payType,
														 @RequestParam(required = false) String remark) {
		try {
			OrderRequestParam requestParam = new OrderRequestParam();
			requestParam.setGoodsIds(goodsIds);
			requestParam.setPayType(payType != null ? payType : 10);
            requestParam.setRemark( remark);
			// 兼容参数占位，当前实现未使用赠品参数
			OrderResponseParam responseParam = orderService.buyNow(requestParam);
			return CommonResult.data(responseParam);
		} catch (Exception e) {
			return CommonResult.error("立即购买失败：" + e.getMessage());
		}
	}

    /**
     * 获取购物车订单
     */
    @GetMapping("/cart")
    @Operation(summary = "获取购物车订单")
    public CommonResult<OrderResponseParam> getCartOrder(@RequestParam(required = false) String cartIds,
                                                        @RequestParam(required = false) String payType,
                                                        @RequestParam(required = false) String source) {
        try {
            OrderResponseParam responseParam = orderService.getCartOrder(cartIds, payType, source);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取购物车订单失败：" + e.getMessage());
        }
    }

    /**
     * 提交订单（购物车结算）
     */
    @PostMapping("/cart")
    @Operation(summary = "提交订单（购物车结算）")
    public CommonResult<OrderResponseParam> submitOrder(@RequestBody OrderRequestParam requestParam) {
        try {
            OrderResponseParam responseParam = orderService.submitOrder(requestParam);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("提交订单失败：" + e.getMessage());
        }
    }

    /**
     * 订单列表
     */
    @GetMapping("/lists")
    @Operation(summary = "订单列表")
    public CommonResult<Page<OrderListVo>> getOrderList(@RequestParam(required = false) String dataType,
                                                        @RequestParam(required = false) Integer source,
                                                        @RequestParam(required = false) Integer time
                                                        ) {
            Page<Order> page = PageFactory.defaultPage();
        try {
            Page<OrderListVo> responseParam= orderService.getOrderList(dataType,source, time,page);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 订单详情
     */
    @GetMapping("/detail/{orderId}")
    @Operation(summary = "订单详情")
    public CommonResult<OrderDetailVo> getOrderDetail(@PathVariable Long orderId) {
        try {
            OrderDetailVo responseParam = orderService.getOrderDetail(orderId);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 取消订单
     */
    @GetMapping("/cancel/{orderId}")
    @Operation(summary = "取消订单")
    public CommonResult<String> cancelOrder(@PathVariable Long orderId) {
        try {
            orderService.cancelOrder(orderId);
            return CommonResult.ok("订单取消成功");
        } catch (Exception e) {
            return CommonResult.error("取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 确认收货
     */
    @PostMapping("/confirm/{orderId}")
    @Operation(summary = "确认收货")
    public CommonResult<String> confirmOrder(@PathVariable Long orderId,
                                            @RequestParam String token) {
        try {
            orderService.confirmOrder(orderId, token);
            return CommonResult.ok("确认收货成功");
        } catch (Exception e) {
            return CommonResult.error("确认收货失败：" + e.getMessage());
        }
    }

    /**
     * 删除订单
     */
    @PostMapping("/delete/{orderId}")
    @Operation(summary = "删除订单")
    public CommonResult<String> deleteOrder(@PathVariable Long orderId,
                                           @RequestParam String token) {
        try {
            orderService.deleteOrder(orderId, token);
            return CommonResult.ok("删除订单成功");
        } catch (Exception e) {
            return CommonResult.error("删除订单失败：" + e.getMessage());
        }
    }

    /**
     * 订单支付
     */
    @PostMapping("/pay/{orderId}")
    @Operation(summary = "订单支付")
    public CommonResult<OrderResponseParam> payOrder(@PathVariable Long orderId,
                                                    @RequestBody OrderRequestParam requestParam) {
        try {
            OrderResponseParam responseParam = orderService.payOrder(orderId, requestParam);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("订单支付失败：" + e.getMessage());
        }
    }

    /**
     * 订单统计
     */
    @GetMapping("/statistics")
    @Operation(summary = "订单统计")
    public CommonResult<OrderResponseParam> getOrderStatistics(@RequestParam String token) {
        try {
            OrderResponseParam responseParam = orderService.getOrderStatistics(token);
            return CommonResult.data(responseParam);
        } catch (Exception e) {
            return CommonResult.error("获取订单统计失败：" + e.getMessage());
        }
    }

    /**
     * 订单审核
     */
    @PostMapping("/audit")
    @Operation(summary = "订单审核")
    public CommonResult<String> auditOrder(@RequestBody OrderAuditBo orderAuditBo){
        try {
            orderService.auditOrder(orderAuditBo.getOrderId(), orderAuditBo.getAuditStatus(), orderAuditBo.getRejectReason());
            return CommonResult.ok("审核操作成功");
        } catch (Exception e) {
            return CommonResult.error("订单审核失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单物流信息
     */
    @GetMapping("/orderExpress/{orderId}")
    @Operation(summary = "获取订单物流信息")
    @SaIgnore
    public CommonResult<Page<OrderExpressVo>> getOrderExpress(@PathVariable Long orderId) {
        Page<OrderExpress> page = PageFactory.defaultPage();
        try {
            Page<OrderExpressVo> result = orderService.getOrderExpress(orderId, page);
            return CommonResult.data(result);
        } catch (Exception e) {
            return CommonResult.error("获取物流信息失败：" + e.getMessage());
        }
    }

    /**
     * 确认收货
     */
    @GetMapping("/receipt")
    @Operation(summary = "确认收货")
    public CommonResult<String> confirmReceipt(@RequestParam Long orderId,
                                              @RequestParam Integer status,
                                              @RequestParam(required = false) String orderExpressId) {
        try {
            orderService.confirmReceipt(orderId, status, orderExpressId);
            return CommonResult.ok("确认收货成功");
        } catch (Exception e) {
            return CommonResult.error("确认收货失败：" + e.getMessage());
        }
    }

    /**
     * 业务员取消订单
     */
    @GetMapping("/salesmanCancel")
    @Operation(summary = "业务员取消订单")
    public CommonResult<String> salesmanCancel(@RequestParam Long orderId,
                                               @RequestParam Integer status,
                                               @RequestParam String rejectReason) {
        try {
            orderService.salesmanCancel(orderId, status,rejectReason);
            return CommonResult.ok("操作成功");
        } catch (Exception e) {
            return CommonResult.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 购物车结算预览接口
     * 对应PHP项目的/order/cart接口的GET请求功能
     * 
     * @param cartIds 购物车ID列表，格式：goods_id_goods_sku_id，多个用逗号分隔
     * @param payType 支付方式：10余额支付，20微信支付，30返利支付，40核销支付
     * @param source 订单来源：10普通订单，30返利订单，40核销订单
     * @return 订单结算预览信息
     */
    @GetMapping("/cart2")
    @Operation(summary = "购物车结算预览", description = "获取购物车订单的结算预览信息，对应PHP的/order/cart GET请求")
    public CommonResult<CartOrderPreviewResponseParam> getCartOrderPreview(
            @RequestParam(required = false) String cartIds,
            @RequestParam(required = false, defaultValue = "10") Integer payType,
            @RequestParam(required = false, defaultValue = "10") Integer source) {
        
        try {
            // 获取购物车订单结算预览信息
            CartOrderPreviewResponseParam previewInfo = orderService.getCartOrderPreview(cartIds, source, payType, source);
            return CommonResult.data(previewInfo);
            
        } catch (Exception e) {
            return CommonResult.error("获取购物车订单预览失败：" + e.getMessage());
        }
    }

    /**
     * 购物车结算预览接口（新接口）
     * 对应PHP项目的/order/cart接口的GET请求功能
     * 
     * @param cartIds 购物车ID列表，格式：goods_id_goods_sku_id，多个用逗号分隔
     * @param isGoodsType 商品类型：10普通订单，30返利订单，40核销订单
     * @param payType 支付方式：10余额支付，20微信支付
     * @param source 订单来源：10普通订单，30返利订单，40核销订单
     * @return 订单结算预览信息
     */
    @GetMapping("/cart/preview")
    @Operation(summary = "购物车结算预览", description = "获取购物车订单的结算预览信息，包含商品列表、价格计算、优惠信息等")
    public CommonResult<CartOrderPreviewResponseParam> getCartOrderPreviewNew(
            @RequestParam(required = false) String cartIds,
            @RequestParam(required = false, defaultValue = "10") Integer isGoodsType,
            @RequestParam(required = false, defaultValue = "10") Integer payType,
            @RequestParam(required = false, defaultValue = "10") Integer source) {
        
        try {
            // 获取购物车订单结算预览信息
            CartOrderPreviewResponseParam previewInfo = orderService.getCartOrderPreview(cartIds, isGoodsType, payType, source);
            return CommonResult.data(previewInfo);
            
        } catch (Exception e) {
            return CommonResult.error("获取购物车订单预览失败：" + e.getMessage());
        }
    }
} 